<?php

namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Lang;
/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Dashboard extends AdminControl {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'admin/lang/'.config('lang.default_lang').'/dashboard.lang.php');
        include_once root_path(). 'extend/mall/statistics.php';
        include_once root_path(). 'extend/mall/datehelper.php';
    }

    function index() {
        $this->welcome();
    }

    /*
     * 检查是否为最新版本
     */

    function version() {
        //当前版本
        $curent_version = file_get_contents(base_path() . 'version.php');
        //获取最新版本信息
        $vaules = array(
            'domain'=>$_SERVER['HTTP_HOST'], 
            'version'=>$curent_version, 
        );
        $service_url = "http://service.csdeshang.com/index.php/home/Version/checkDsmall.html?".http_build_query($vaules);
        //设置超时时间
        $opts = array(
            'http' =>
            array(
                'timeout' => 3
            )
        );
        $context = stream_context_create($opts);
        $service_info = @file_get_contents($service_url,FALSE,$context);
        $version_message = json_decode($service_info);
        View::assign('version_message', $version_message);
    }

    function welcome() {
        $this->version();
        /**
         * 管理员信息
         */
        $admin_model = model('admin');
        $tmp = $this->getAdminInfo();
        $condition = array();
        $condition[] = array('admin_id','=',$tmp['admin_id']);
        $admin_info = $admin_model->infoAdmin($condition);
        $admin_info['admin_login_time'] = date('Y-m-d H:i:s', ($admin_info['admin_login_time'] == '' ? TIMESTAMP : $admin_info['admin_login_time']));
        /**
         * 系统信息
         */
        $setup_date = config('ds_config.setup_date');
        $statistics['tp_version'] = \think\App::VERSION;
        $statistics['os'] = PHP_OS;
        $statistics['web_server'] = $_SERVER['SERVER_SOFTWARE'];
        $statistics['php_version'] = PHP_VERSION;
        $statistics['sql_version'] = $this->_mysql_version();
        //$statistics['shop_version'] = $version;
        $statistics['setup_date'] = substr($setup_date, 0, 10);

        $statistics['domain'] = $_SERVER['HTTP_HOST'];
        $statistics['ip'] = GetHostByName($_SERVER['SERVER_NAME']);
        $statistics['zlib'] = function_exists('gzclose') ? 'YES' : 'NO'; //zlib
        $statistics['safe_mode'] = (boolean) ini_get('safe_mode') ? 'YES' : 'NO'; //safe_mode = Off
        $statistics['timezone'] = function_exists("date_default_timezone_get") ? date_default_timezone_get() : "no_timezone";
        $statistics['curl'] = function_exists('curl_init') ? 'YES' : 'NO';
        $statistics['fileupload'] = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 'unknown';
        $statistics['max_ex_time'] = @ini_get("max_execution_time") . 's'; //脚本最大执行时间
        $statistics['set_time_limit'] = function_exists("set_time_limit") ? true : false;
        $statistics['memory_limit'] = ini_get('memory_limit');
        $statistics['version'] = file_get_contents(base_path() . 'version.php');
        if (function_exists("gd_info")) {
            $gd = gd_info();
            $statistics['gdinfo'] = $gd['GD Version'];
        } else {
            $statistics['gdinfo'] = lang('ds_unknown');
        }

        View::assign('statistics', $statistics);
        View::assign('admin_info', $admin_info);
        $this->_stat_json();
        $this->setAdminCurItem('welcome');
        echo View::fetch('welcome');
        exit;
    }
    private function _stat_json()
    {
        $this->_get_week_member();
        $this->_get_week_goods();
        $this->_get_week_store();
        $this->_get_week_order();
    }
     /**
     * 获取本周新增订单数量
     */
    private function _get_week_order()
    {
        $field = ' COUNT(*) as allnum ';
        $current_weekarr = getWeek_SdateAndEdate(TIMESTAMP);
        $stime = strtotime($current_weekarr['sdate']) - 86400 * 7;
        $etime = strtotime($current_weekarr['edate']) + 86400 - 1;
        //总计的查询时间
        $count_arr['seartime'] = ($stime + 86400 * 7) . '|' . $etime;

        $up_week = @date('W', $stime); //上周
        $curr_week = @date('W', $etime); //本周
        //构造横轴数据
        for ($i = 1; $i <= 7; $i++) {
            //统计图数据
            $up_arr[$i] = 0;
            $curr_arr[$i] = 0;
            $tmp_weekarr = getSystemWeekArr();
            //统计表数据
            $currlist_arr[$i]['timetext'] = $tmp_weekarr[$i];
            //方便搜索会员列表，计算开始时间和结束时间
            $currlist_arr[$i]['stime'] = strtotime($current_weekarr['sdate']) + ($i - 1) * 86400;
            $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

            $uplist_arr[$i]['val'] = 0;
            $currlist_arr[$i]['val'] = 0;
            //横轴
            $stat_arr['xAxis']['categories'][] = $tmp_weekarr[$i];
            unset($tmp_weekarr);
        }
        $where = array();
        $where[] = array('add_time','between', array($stime, $etime));
        $field .= ',WEEKOFYEAR(FROM_UNIXTIME(add_time)) as weekval,WEEKDAY(FROM_UNIXTIME(add_time))+1 as dayofweekval ';
        
        $orderlist = Db::name('order')->field($field)->where($where)->group('weekval,dayofweekval')->select()->toArray();

        if ($orderlist) {
            foreach ($orderlist as $k => $v) {
                if ($up_week == intval($v['weekval'])) {
                    $up_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $uplist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['up'])){
                        $count_arr['up'] += intval($v['allnum']);
                    }else{
                        $count_arr['up'] = 0;
                    }
                }
                if ($curr_week == $v['weekval']) {
                    $curr_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $currlist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['curr'])){
                        $count_arr['curr'] += intval($v['allnum']);
                    }else{
                        $count_arr['curr'] = 0;
                    }
                }
            }
        }

        $stat_arr['series'][0]['name'] = lang('last_week');
        $stat_arr['series'][0]['data'] = array_values($up_arr);
        $stat_arr['series'][1]['name'] = lang('this_week');
        $stat_arr['series'][1]['data'] = array_values($curr_arr);

        //得到统计图数据
        $stat_arr['title'] = lang('new_order_statistics');
        $stat_arr['yAxis'] = lang('new_order_count');
        $stat_json = getStatData_LineLabels($stat_arr);
        View::assign('stat_json_week_order', $stat_json);
    }
        /**
     * 获取本周新增店铺数量
     */
    private function _get_week_store()
    {
        $field = ' COUNT(*) as allnum ';
        $current_weekarr = getWeek_SdateAndEdate(TIMESTAMP);
        $stime = strtotime($current_weekarr['sdate']) - 86400 * 7;
        $etime = strtotime($current_weekarr['edate']) + 86400 - 1;
        //总计的查询时间
        $count_arr['seartime'] = ($stime + 86400 * 7) . '|' . $etime;

        $up_week = @date('W', $stime); //上周
        $curr_week = @date('W', $etime); //本周
        //构造横轴数据
        for ($i = 1; $i <= 7; $i++) {
            //统计图数据
            $up_arr[$i] = 0;
            $curr_arr[$i] = 0;
            $tmp_weekarr = getSystemWeekArr();
            //统计表数据
            $currlist_arr[$i]['timetext'] = $tmp_weekarr[$i];
            //方便搜索会员列表，计算开始时间和结束时间
            $currlist_arr[$i]['stime'] = strtotime($current_weekarr['sdate']) + ($i - 1) * 86400;
            $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

            $uplist_arr[$i]['val'] = 0;
            $currlist_arr[$i]['val'] = 0;
            //横轴
            $stat_arr['xAxis']['categories'][] = $tmp_weekarr[$i];
            unset($tmp_weekarr);
        }
        $where = array();
        $where[] = array('store_addtime','between', array($stime, $etime));
        $field .= ',WEEKOFYEAR(FROM_UNIXTIME(store_addtime)) as weekval,WEEKDAY(FROM_UNIXTIME(store_addtime))+1 as dayofweekval ';
        
        $storelist = Db::name('store')->field($field)->where($where)->group('weekval,dayofweekval')->select()->toArray();

        if ($storelist) {
            foreach ($storelist as $k => $v) {
                if ($up_week == intval($v['weekval'])) {
                    $up_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $uplist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['up'])){
                        $count_arr['up'] += intval($v['allnum']);
                    }else{
                        $count_arr['up'] = 0;
                    }
                }
                if ($curr_week == $v['weekval']) {
                    $curr_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $currlist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['curr'])){
                        $count_arr['curr'] += intval($v['allnum']);
                    }else{
                        $count_arr['curr'] = 0;
                    }
                }
            }
        }

        $stat_arr['series'][0]['name'] = lang('last_week');
        $stat_arr['series'][0]['data'] = array_values($up_arr);
        $stat_arr['series'][1]['name'] = lang('this_week');
        $stat_arr['series'][1]['data'] = array_values($curr_arr);

        //得到统计图数据
        $stat_arr['title'] = lang('new_store_statistics');
        $stat_arr['yAxis'] =  lang('new_store_count');
        $stat_json = getStatData_LineLabels($stat_arr);
        View::assign('stat_json_week_store', $stat_json);
    }

    /**
     * 获取本周新增商品数量
     */
    private function _get_week_goods() {
        $field = ' COUNT(*) as allnum ';
        $current_weekarr = getWeek_SdateAndEdate(TIMESTAMP);
        $stime = strtotime($current_weekarr['sdate']) - 86400 * 7;
        $etime = strtotime($current_weekarr['edate']) + 86400 - 1;
        //总计的查询时间
        $count_arr['seartime'] = ($stime + 86400 * 7) . '|' . $etime;

        $up_week = @date('W', $stime); //上周
        $curr_week = @date('W', $etime); //本周
        //构造横轴数据
        for ($i = 1; $i <= 7; $i++) {
            //统计图数据
            $up_arr[$i] = 0;
            $curr_arr[$i] = 0;
            $tmp_weekarr = getSystemWeekArr();
            //统计表数据
            $currlist_arr[$i]['timetext'] = $tmp_weekarr[$i];
            //方便搜索会员列表，计算开始时间和结束时间
            $currlist_arr[$i]['stime'] = strtotime($current_weekarr['sdate']) + ($i - 1) * 86400;
            $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

            $uplist_arr[$i]['val'] = 0;
            $currlist_arr[$i]['val'] = 0;
            //横轴
            $stat_arr['xAxis']['categories'][] = $tmp_weekarr[$i];
            unset($tmp_weekarr);
        }
        $where = array();
        $where[] = array('goods_addtime','between', array($stime, $etime));
        $field .= ',WEEKOFYEAR(FROM_UNIXTIME(goods_addtime)) as weekval,WEEKDAY(FROM_UNIXTIME(goods_addtime))+1 as dayofweekval ';
        
        $goodslist = Db::name('goodscommon')->field($field)->where($where)->group('weekval,dayofweekval')->select()->toArray();

        if ($goodslist) {
            foreach ($goodslist as $k => $v) {
                if ($up_week == intval($v['weekval'])) {
                    $up_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $uplist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['up'])){
                        $count_arr['up'] += intval($v['allnum']);
                    }else{
                        $count_arr['up'] = 0;
                    }
                }
                if ($curr_week == $v['weekval']) {
                    $curr_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $currlist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['curr'])){
                        $count_arr['curr'] += intval($v['allnum']);
                    }else{
                        $count_arr['curr'] = 0;
                    }
                }
            }
        }
        
        

        $stat_arr['series'][0]['name'] = lang('last_week');
        $stat_arr['series'][0]['data'] = array_values($up_arr);
        $stat_arr['series'][1]['name'] = lang('this_week');
        $stat_arr['series'][1]['data'] = array_values($curr_arr);

        //得到统计图数据
        $stat_arr['title'] = lang('new_goods_statistics');
        $stat_arr['yAxis'] = lang('new_goods_count');
        $stat_json = getStatData_LineLabels($stat_arr);
        View::assign('stat_json_week_goods', $stat_json);
    }
    
     /**
     * 获取本周新增会员数量
     */
    private function _get_week_member() {
        $field = ' COUNT(*) as allnum ';
        $current_weekarr = getWeek_SdateAndEdate(TIMESTAMP);
        $stime = strtotime($current_weekarr['sdate']) - 86400 * 7;
        $etime = strtotime($current_weekarr['edate']) + 86400 - 1;
        //总计的查询时间
        $count_arr['seartime'] = ($stime + 86400 * 7) . '|' . $etime;

        $up_week = @date('W', $stime); //上周
        $curr_week = @date('W', $etime); //本周
        //构造横轴数据
        for ($i = 1; $i <= 7; $i++) {
            //统计图数据
            $up_arr[$i] = 0;
            $curr_arr[$i] = 0;
            $tmp_weekarr = getSystemWeekArr();
            //统计表数据
            $currlist_arr[$i]['timetext'] = $tmp_weekarr[$i];
            //方便搜索会员列表，计算开始时间和结束时间
            $currlist_arr[$i]['stime'] = strtotime($current_weekarr['sdate']) + ($i - 1) * 86400;
            $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

            $uplist_arr[$i]['val'] = 0;
            $currlist_arr[$i]['val'] = 0;
            //横轴
            $stat_arr['xAxis']['categories'][] = $tmp_weekarr[$i];
            unset($tmp_weekarr);
        }
        $where = array();
        $where[] = array('member_addtime','between', array($stime, $etime));
        $field .= ',WEEKOFYEAR(FROM_UNIXTIME(member_addtime)) as weekval,WEEKDAY(FROM_UNIXTIME(member_addtime))+1 as dayofweekval ';
        $memberlist = Db::name('member')->field($field)->where($where)->group('weekval,dayofweekval')->select()->toArray();

        if ($memberlist) {
            foreach ($memberlist as $k => $v) {
                if ($up_week == intval($v['weekval'])) {
                    $up_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $uplist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['up'])){
                        $count_arr['up'] += intval($v['allnum']);
                    }else{
                        $count_arr['up'] = 0;
                    }
                }
                if ($curr_week == $v['weekval']) {
                    $curr_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $currlist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    if(isset($count_arr['curr'])){
                        $count_arr['curr'] += intval($v['allnum']);
                    }else{
                        $count_arr['curr'] = 0;
                    }
                }
            }
        }
        
        $stat_arr['series'][0]['name'] = lang('last_week');
        $stat_arr['series'][0]['data'] = array_values($up_arr);
        $stat_arr['series'][1]['name'] = lang('this_week');
        $stat_arr['series'][1]['data'] = array_values($curr_arr);

        //得到统计图数据
        $stat_arr['title'] = lang('new_member_statistics');
        $stat_arr['yAxis'] = lang('new_member_count');
        $stat_json = getStatData_LineLabels($stat_arr);
        View::assign('stat_json_week_member', $stat_json);
    }

    /**
     * 获取当前数据库版本
     */
    private function _mysql_version() {
        $version = Db::query("select version() as ver");
        return $version[0]['ver'];
    }

    function aboutus() {
        $this->setAdminCurItem('aboutus');
        return View::fetch();
    }

    /**
     * 统计
     */
    public function statistics() {
        $statistics = array();
        // 本周开始时间点
        $tmp_time = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - (date('w') == 0 ? 7 : date('w') - 1) * 24 * 60 * 60;
        /**
         * 会员
         */
        $member_model = model('member');
        // 会员总数
        $statistics['member'] = $member_model->getMemberCount(array());
        // 新增会员数
        $statistics['week_add_member'] = $member_model->getMemberCount(array(array('member_addtime','>=', $tmp_time)));
        // 预存款提现
        $statistics['cashlist'] = model('predeposit')->getPdcashCount(array('pdc_payment_state' => 0));

        /**
         * 店铺
         */
        $store_model = model('store');
        // 店铺总数
        $statistics['store'] = model('store')->getStoreCount(array());
        // 店铺申请数
        $statistics['store_joinin'] = model('storejoinin')->getStorejoininCount(array(array('joinin_state','in', array(10, 11))));
        //经营类目申请
        $statistics['store_bind_class_applay'] = model('storebindclass')->getStorebindclassCount(array('storebindclass_state' => 0));
        //店铺续签申请
        $statistics['store_reopen_applay'] = model('storereopen')->getStorereopenCount(array('storereopen_state' => 1));
        // 即将到期
        $statistics['store_expire'] = $store_model->getStoreCount(array(array('store_state','=',1),array('store_endtime','between',array(TIMESTAMP, TIMESTAMP + 864000))));
        // 已经到期
        $statistics['store_expired'] = $store_model->getStoreCount(array(array('store_state','=',1),array('store_endtime','between',array(1, TIMESTAMP))));

        /**
         * 商品
         */
        $goods_model = model('goods');
        // 商品总数
        $statistics['goods'] = $goods_model->getGoodsCommonCount(array());
        // 新增商品数
        $statistics['week_add_product'] = $goods_model->getGoodsCommonCount(array(array('goods_addtime','>=', $tmp_time)));
        // 等待审核
        $statistics['product_verify'] = $goods_model->getGoodsCommonWaitVerifyCount(array());
        // 举报
        $statistics['inform_list'] = model('inform')->getInformCount(array('inform_state' => 1));
        // 品牌申请
        $statistics['brand_apply'] = model('brand')->getBrandCount(array('brand_apply' => '0'));

        /**
         * 交易
         */
        $order_model = model('order');
        $refundreturn_model = model('refundreturn');
        $vrrefund_model = model('vrrefund');
        $complain_model = model('complain');
        // 订单总数
        $statistics['order'] = $order_model->getOrderCount(array());
        // 退款
        $statistics['refund'] = $refundreturn_model->getRefundreturnCount(array('refund_type' => 1, 'refund_state' => 2));
        // 退货
        $statistics['return'] = $refundreturn_model->getRefundreturnCount(array('refund_type' => 2, 'refund_state' => 2));
        // 虚拟订单退款
        $statistics['vr_refund'] = $vrrefund_model->getVrrefundCount(array('admin_state' => 1));
        // 投诉
        $statistics['complain_new_list'] = $complain_model->getComplainCount(array('complain_state' => 10));
        // 待仲裁
        $statistics['complain_handle_list'] = $complain_model->getComplainCount(array('complain_state' => 40));

        /**
         * 运营
         */
        // 抢购数量
        $statistics['groupbuy_verify_list'] = model('groupbuy')->getGroupbuyCount(array('groupbuy_state' => 10));
        // 积分订单
        $pointsorder_model = model('pointorder');
        $condition =array();
        $condition =array(array('point_orderstate','in', array(11, 20)));
        $statistics['points_order'] = $pointsorder_model->getPointorderCount($condition);
        //待审核账单
        $bill_model = model('bill');
        $statistics['check_billno'] = $bill_model->getOrderbillCount(array('ob_state'=>BILL_STATE_STORE_COFIRM));
        //待支付账单
        $statistics['pay_billno'] = $bill_model->getOrderbillCount(array('ob_state'=>BILL_STATE_STORE_COFIRM));
        // 平台客服
        $statistics['mall_consult'] = model('mallconsult')->getMallconsultCount(array('mallconsult_isreply' => 0));
        // 服务站
        $statistics['delivery_point'] = model('deliverypoint')->getDeliverypointWaitVerifyCount(array());

        echo json_encode($statistics);
        exit;
    }

}

?>
